/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.util;

import org.apache.commons.beanutils.BeanComparator;

import java.util.*;

public class CollectionUtils {
  public static <T> List<T> reverse(List<T> list) {
    List<T> newList = new ArrayList<T>(list);
    Collections.reverse(newList);
    return newList;
  }

  public static boolean containsStr(String collection, String item) {
    return collection != null && contains(new HashSet<String>(Arrays.asList(collection.split(","))), item);
  }

  public static <T> boolean contains(Collection<T> values, T item) {
    return values != null && item != null && values.contains(item);
  }

  public static List sublist(List items, int max) {
    return items.size() >= max ? items.subList(0, max) : items;
  }

  public static <T> List<T> sort(Collection<T> items, String property) {
    return sort(items, new BeanComparator(property));
  }

  public static <T> List<T> sortDesc(Collection<T> items, String property) {
    return sort(items, Collections.reverseOrder(new BeanComparator(property)));
  }

  private static <T> List<T> sort(Collection<T> items, Comparator<T> comparator) {
    if (items != null) {
      List<T> newList = new ArrayList<T>();
      newList.addAll(items);
      Collections.sort(newList, comparator);
      return newList;
    }
    return null;
  }


  public static <T> Collection<T> doFilter(Collection<T> values, Predicate<T> predicate) {
    Collection<T> results = new ArrayList<T>();
    for (T value : values) {
      if (predicate.qualifies(value)) {
        results.add(value);
      }
    }
    return results;
  }

  public static int size(Collection items) {
    return items == null ? 0 : items.size();
  }

  public static <T,V> List<V> map(List<T> source, Producer<T,V> lambda) {
    List<V> results = new LinkedList<V>();
    for(T element : source) {
      results.add(lambda.produce(element));
    }
    return results;
  }
   public interface Producer<T, V> {
        V produce(T from);
    }

}
